/* 输入框数字保留2位小数（四舍五入）-指令 */
export default {
  inserted: (el, binding) => {
    // 保留的小数位数
    const decimal = binding.value ? binding.value : 2;
    if (el.tagName.toLocaleUpperCase() !== "INPUT") {
      el =
        el.getElementsByTagName("input") && el.getElementsByTagName("input")[0];
    }

    if (!el) {
      return;
    }

    el.addEventListener("keypress", e => {
      e = e || window.event;
      let charcode = typeof e.charCode === "number" ? e.charCode : e.keyCode;
      let re = /\d/;
      if (charcode === 46) {
        if (el && el.value && el.value.includes(".")) {
          e.preventDefault();
        }
      } else if (
        !re.test(String.fromCharCode(charcode)) &&
        charcode > 9 &&
        !e.ctrlKey
      ) {
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          e.returnValue = false;
        }
      }
    });

    el.addEventListener("blur", e => {
      let val = Number(el.value);
      if (!isNaN(val)) {
        let event = document.createEvent("HTMLEvents");
        event.initEvent("input", false, true);
        if (val > 99999999999999999) {
          el.value = "数值过大";
          el.dispatchEvent(event);
          return;
        }
        if (el.value.includes(".")) {
          let times = Math.pow(10, decimal);
          let roundNum = Math.round(val * times) / times;
          el.value = roundNum.toFixed(decimal);
          el.dispatchEvent(event);
        }
      }
    });
  }
};
